"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : GUC_ErrorLog
Case Name   : debug_print_plan设置为on，log日志查询特定SQL语句执行计划打印正常
Create At   : 2023/2/18
Owner       : opentestcase024
Description :
    0、修改参数log_directory;
    1、修改参数log_min_messages为info;
    2、重启数据库,重新生成pg_log;
    3、执行建表SQL;
    4、修改参数debug_print_plan为on;
    5、执行特定SQL语句;
    6、查看pg日志;
    baselocatortype为'\0'未被截断。不存在:baselocatortype结尾的行
Expect      :
    0、修改参数log_directory; expect:修改成功
    1、修改参数log_min_messages为info; expect:修改成功
    2、重启数据库,重新生成pg_log; expect:重启成功
    3、执行建表SQL expect：成功
    4、修改参数debug_print_plan为on; expect:修改成功
    5、执行特定SQL语句 expect：成功
    6、查看pg日志; expect：不存在:baselocatortype结尾的行
History     :
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class ErrorLog(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)}:start----')
        self.pri_dbuser = Node('PrimaryDbUser')
        self.pri_root = Node('PrimaryRoot')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.com = Common()
        self.constant = Constant()
        self.tb_name = 't_guc_errorlog_case0131'
        self.dir_new = os.path.join(macro.PG_LOG_PATH, 'pg_bak',
                                    'pg_errorlog_case0131')

    def test_main(self):
        step_txt = '----查看参数默认值----'
        self.log.info(step_txt)
        self.init_dir = self.com.show_param("log_directory")
        self.init_para1 = self.com.show_param("log_min_messages")
        self.init_para2 = self.com.show_param("debug_print_plan")

        step_txt = '----step0:修改参数log_directory; expect:修改成功----'
        self.log.info(step_txt)
        msg = self.pri_sh.execute_gsguc('reload',
                                        self.constant.GSGUC_SUCCESS_MSG,
                                        f"log_directory='{self.dir_new}'",
                                        single=True)
        self.assertTrue(msg, '执行失败:' + step_txt)

        step_txt = '----step1:修改参数log_min_messages为info; expect:修改成功----'
        self.log.info(step_txt)
        msg = self.pri_sh.execute_gsguc('reload',
                                        self.constant.GSGUC_SUCCESS_MSG,
                                        f"log_min_messages='info'",
                                        single=True)
        self.assertTrue(msg, '执行失败:' + step_txt)

        step_txt = '----step2:重启数据库,重新生成pg_log; expect:重启成功----'
        self.log.info(step_txt)
        restart = self.pri_sh.restart_db_cluster()
        self.assertTrue(restart, '执行失败:' + step_txt)

        step_txt = '----step3:执行建表SQL expect：成功----'
        self.log.info(step_txt)
        create_db = f'drop table if exists {self.tb_name};' \
            f'create table {self.tb_name} (id int,dir text);'
        create_result = self.pri_sh.execut_db_sql(create_db)
        self.log.info(create_result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_result,
                      '执行失败:' + step_txt)

        step_txt = '----step4:修改参数debug_print_plan为on; expect:修改成功----'
        self.log.info(step_txt)
        msg = self.pri_sh.execute_gsguc('reload',
                                        self.constant.GSGUC_SUCCESS_MSG,
                                        f"debug_print_plan='on'",
                                        single=True)
        self.assertTrue(msg, '执行失败:' + step_txt)

        step_txt = '----step5:执行特定SQL语句 expect：成功----'
        self.log.info(step_txt)
        select_sql = f'select sample_0.classoid as c0, 6 as c1, ' \
            f'sample_0.xc_node_id as c2 from pg_catalog.pg_seclabel ' \
            f'as sample_0 where ((((EXISTS ( select sample_0.classoid ' \
            f'as c0,sample_1.dir as c2, sample_1.dir as c3 from ' \
            f'{self.tb_name} as sample_1 where (select proargtypes from ' \
            f'pg_catalog.pg_proc limit 1 offset 4) = ' \
            f'(select indcollation from pg_catalog.pg_index limit 1))))));'
        select_result = self.pri_sh.execut_db_sql(select_sql)
        self.log.info(select_result)
        self.assertIn('0 rows', select_result, '执行失败:' + step_txt)

        self.log.info('----step6:查看pg日志; expect：不存在:baselocatortype结尾的行----')
        shell_cmd = f'ls -t {self.dir_new} | head -1'
        file_name = os.path.join(self.dir_new,
                                 self.pri_root.sh(shell_cmd).result())
        self.log.info(file_name)
        shell_cmd = f"grep -n ':baselocatortype $' {file_name}"
        self.log.info(shell_cmd)
        shell_result = self.pri_dbuser.sh(shell_cmd).result()
        self.log.info(shell_result)
        self.assertEqual('', shell_result, '执行失败:' + step_txt)

    def tearDown(self):
        self.log.info('----this is teardown----')
        step1_txt = '----删除数据库 expect: 成功----'
        self.log.info(step1_txt)
        drop_sql = f"drop table if exists {self.tb_name};"
        drop_result = self.pri_sh.execut_db_sql(drop_sql)
        self.log.info(drop_result)

        step2_txt = '----还原参数log_directory; expect:修改成功----'
        self.log.info(step2_txt)
        msg2 = self.pri_sh.execute_gsguc('reload',
                                         self.constant.GSGUC_SUCCESS_MSG,
                                         f"log_directory='{self.init_dir}'",
                                         single=True)

        step_txt = '----还原参数log_min_messages为info; expect:修改成功----'
        self.log.info(step_txt)
        msg3 = self.pri_sh.execute_gsguc('reload',
                                         self.constant.GSGUC_SUCCESS_MSG,
                                         f"log_min_messages="
                                         f"'{self.init_para1}'",
                                         single=True)

        step_txt = '----还原参数debug_print_plan为on; expect:修改成功----'
        self.log.info(step_txt)
        msg4 = self.pri_sh.execute_gsguc('reload',
                                         self.constant.GSGUC_SUCCESS_MSG,
                                         f"debug_print_plan="
                                         f"'{self.init_para2}'",
                                         single=True)

        step_txt = '----断言teardown执行成功----'
        self.log.info(step_txt)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_result,
                      step1_txt)
        self.assertTrue(msg2, '执行失败:' + step2_txt)
        self.assertTrue(msg3, '执行失败:' + step_txt)
        self.assertTrue(msg4, '执行失败:' + step_txt)

        self.log.info(f'----{os.path.basename(__file__)}:end----')
